/**
 * 
 */
package com.alstudio.ui.module.voip;

import java.io.IOException;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.voip.ALVoipCallManager;
import com.alstudio.core.voip.CallState;
import com.alstudio.module.voip.ALVoipEvent;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.dating.DatingUser;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.user.UserIconsUtil;
import com.alstudio.view.animation.AnimationEndListener;
import com.alstudio.view.image.ALRoundImageDisplayer;
import com.alstudio.view.listener.ALViewOnTouchManager;
import com.alstudio.view.listener.ALViewOnTouchManager.OnALTouchStateListener;
import com.alstudio.view.text.AnimateTextView;
import com.alstudio.view.text.AnimateTextView.AnimateListener;
import com.loovee.imaohu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * 邂逅界面
 * 
 * @author alonso lee
 * 
 */
public class XieHouActivity extends TitleBarActivity implements
		OnALTouchStateListener {

	private DatingUser mDatingUser;
	// 大头像
	private ImageView large_icon;

	private View change, call, icon_layout, large_icon_section, middle_layout;

	private LinearLayout img_layout;

	private FrameLayout anim_layout;

	private FlakeView flakeView;

	private DisplayImageOptions cycleImageDisplayOptions;

	private ALViewOnTouchManager seekTouchManager;

	private ALXmppEvent seekEvent;

	private AnimateTextView nick, age_location, money;

	private ImageView large_meteor;

	private MeteorView meteorView;
	private MeteorView2 flashView;

	private GifImageView gif;

	private GifDrawable gd;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context,
	 * java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarContentView(R.layout.xiehou_layout);
		hideTitleBar();
		img_layout = (LinearLayout) findViewById(R.id.img_layout);
		anim_layout = (FrameLayout) findViewById(R.id.anim_layout);
		large_icon = (ImageView) findViewById(R.id.large_icon);
		// 下一个
		change = findViewById(R.id.change);
		// 拨号
		call = findViewById(R.id.call);

		icon_layout = findViewById(R.id.icon_layout);

		large_icon_section = findViewById(R.id.large_icon_section);

		middle_layout = findViewById(R.id.middle_layout);

		setViewOnclickListener(call, this);
		call.setEnabled(false);

		nick = (AnimateTextView) findViewById(R.id.nick);
		age_location = (AnimateTextView) findViewById(R.id.age_location);
		money = (AnimateTextView) findViewById(R.id.money);

		large_meteor = (ImageView) findViewById(R.id.large_meteor);

		nick.setListener(nickAnimateListener);
		age_location.setListener(ageLocationAnimateListener);
		money.setListener(moneyAnimateListener);

		// flakeView = new FlakeView(this);
		// flakeView.addFlakes(100);
		goneView(R.id.no_user);
		goneView(R.id.icon_layout);

		gif = (GifImageView) findViewById(R.id.giv);
		// gif.setImageDrawable(Uri.parse(uriString))

		try {
			gd = new GifDrawable(getAssets(), "galaxy.gif");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		meteorView = new MeteorView(getApplicationContext());
		flashView = new MeteorView2(getApplicationContext());
		// meteorView.addMeteor(10);
		// flashView.addMeteor(500);
		anim_layout.addView(meteorView);
		anim_layout.addView(flashView);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		// 圆形图片显示配置
		cycleImageDisplayOptions = new DisplayImageOptions.Builder()
				./* delayBeforeLoading(1000). */cacheInMemory(false)
				// 加入内存缓存
				.cacheOnDisc(true)
				// 加入sd卡缓存
				.showImageOnLoading(R.drawable.meet_flash_user_star_01_empty)
				.showImageForEmptyUri(R.drawable.meet_flash_user_star_01_empty)
				.showImageOnFail(R.drawable.meet_flash_user_star_01_empty)
				.displayer(new ALRoundImageDisplayer(100)) // 圆形图片显示
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		seekTouchManager = new ALViewOnTouchManager(change, this);

		initAnimation();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#invokeClearActivityEnv()
	 */
	@Override
	public void invokeClearActivityEnv() {
		// TODO Auto-generated method stub
		super.invokeClearActivityEnv();
		seekTouchManager.detach();
		seekTouchManager = null;
		ALLocalEnv.getLocalEnv().clearImageLoaderMemoryCache();
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// meteorView.resume();
		// flashView.resume();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// meteorView.pause();
		// flashView.pause();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		gif.setImageDrawable(null);
		if (gd != null) {
			gd.recycle();

		}
		gd = null;
		meteorView.destroy();
		meteorView.destroyDrawingCache();
		meteorView = null;
		flashView.destroy();
		flashView.destroyDrawingCache();
		flashView = null;
	}

	@Override
	public void handleEnterXieHouEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleEnterXieHouEvent(data);
		if (seekState != START_SEEK)
			return;
		isDataReceived = true;
		seekEvent = data;
	}

	@Override
	public void requeqtData() {
		// TODO Auto-generated method stub
		super.requeqtData();
		if (ALLocalEnv.isSendXmppDataEnable()) {
			showLoadingProgress();
			ALUiXmppRequestCreator.postALUiXmppXiehou();
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// setupUserInfo();
		// requeqtData();
		initGalaxyAnim();
	}

	private boolean isGalaxyAnimInited = false;

	/**
	 * 初始化星空动画
	 */
	private void initGalaxyAnim() {
		if (!isGalaxyAnimInited) {
			isGalaxyAnimInited = true;
			meteorView.addMeteor(10);
			flashView.addMeteor(1000);
			goneView(flashView);
			goneView(meteorView);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		// switch (v.getId()) {
		// case R.id.btn_back:
		// finish();
		// break;
		// case R.id.btn_opt:
		// // 彈出對話框
		// break;
		// case R.id.record_btn:
		// // 錄音
		// ALAudioRecordTask task = new ALAudioRecordTask(this);
		// task.showRecordWindow(findViewById(R.id.content_layout));
		// break;
		// case R.id.play_pic:
		// // 播放、暫停圖片
		// break;
		// case R.id.mute:
		// // 靜音
		// break;
		// case R.id.edit_nick_layout:
		// // 点击编辑签名
		// break;
		// case R.id.nick_layout:
		// // 查看详情
		// break;
		// case R.id.img_layout:
		// // 查看圖片
		// break;
		// case R.id.goto_photos:
		// Intent intent = new Intent(this, PhotoActivity.class);
		// intent.putExtra("mDatingUser", mDatingUser);
		// startActivity(intent);
		// break;
		// case R.id.call:
		// meteorView.addMeteor(10);
		// break;
		// case R.id.change:
		// // 换一个
		// break;
		//
		// default:
		// break;
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		ALLocalEnv.getLocalEnv().clearImageLoaderMemoryCache();
	}

	/**************************************** 用户资料显示 ***************************************************/

	/**
	 * 
	 */
	private void setupUserInfo() {
		if (mDatingUser == null)
			return;
		// 更新是否可以点击切换下一个
		// change.setEnabled(hasMoreUser);

		// 设置昵称
		// showTextMessage(R.id.nick, mDatingUser.getNick());
		// 年龄地区
		// showTextMessage(R.id.age_location, mDatingUser.getAge() + " "
		// + mDatingUser.getLocation());
		// // 顯示性別之類
		UserIconsUtil.setupIconsLayout(img_layout, mDatingUser);
		invisibleView(img_layout);

		String imgFileId = mDatingUser.getImageFileId();

		// 显示大头像
		ALLocalEnv.getLocalEnv().displayImagePluginServerlet(imgFileId,
				large_icon, cycleImageDisplayOptions);

	}

	/******************************** 打电话 **************************************/
	public void onALEvent(ALVoipEvent event) {
		if (!isActivityOn()) {
			return;
		}
		switch (event.getEventType()) {
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_SUCCESS:
			ALUiXmppRequestCreator.postALUiXmppMakeCall(mDatingUser.getJid(),
					ALUiXmppRequestCreator.MAKE_NORMAL_CALL);
			break;
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_FAIL:
			break;
		case ALVOIP_EVENT_START_STREAM_TO_REMOTE_USER:
			break;
		case ALVOIP_EVENT_STOP_STREAM_TO_REMOTE_USER:
			break;
		default:
			break;
		}
	}

	@Override
	public void handleMakeCallEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleMakeCallEvent(data);
		if (data.getResponseCode() == 0) {
			Intent i = new Intent(this, CallActivity.class);
			data.getMessage().setData(mDatingUser);
			i.putExtra("msg", data.getMessage());
			startActivity(i);
			ALVoipCallManager.getDefaultALVoipManager().onCallStateChanged(
					CallState.CALL_OUTGOING, data.getMessage());

		} else {
			showMakeCallErrorToast(data.getResponseCode());
		}
	}

	private int seekState = -1;
	private final int START_SEEK = 0;
	private final int STOP_SEEK = 1;

	private Animation starInAnimation;
	private Animation iconAnimation;
	private Animation dismissAnimation;
	private Animation sexIconAnimation;

	private Animation largeMeteorAnimation;

	private void startGalaxyAnim() {
		// showView(flashView);
		showView(meteorView);
		meteorView.resume();
		// flashView.resume();
	}

	private void stopGalaxyAnim() {
		meteorView.pause();
		// flashView.pause();
		// goneView(flashView);
		goneView(meteorView);
	}

	private Runnable largeMeteorTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			showView(large_meteor);
			large_meteor.startAnimation(largeMeteorAnimation);
			if (seekState == START_SEEK) {
				startLargeMeteorTask();
			}
		}
	};

	private void startLargeMeteorTask() {
		mhandler.postDelayed(largeMeteorTask, 3000);
	}

	private void stopLargeMeteorTask() {
		mhandler.removeCallbacks(largeMeteorTask);
		large_meteor.clearAnimation();
		goneView(large_meteor);
	}

	private AnimationEndListener largeMeteorAnimateListener = new AnimationEndListener() {

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			goneView(large_meteor);
		}
	};

	private AnimationEndListener largeIconAnimateListener = new AnimationEndListener() {

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			nick.animateText(mDatingUser.getNick());
		}
	};

	private AnimationEndListener sexIconAnimateListener = new AnimationEndListener() {

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			age_location.animateText(mDatingUser.getAge() + " "
					+ mDatingUser.getLocation());
		}
	};

	private void initAnimation() {
		starInAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.zoom_in);
		dismissAnimation = AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.zoom_in_2);
		iconAnimation = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.fade_in);
		iconAnimation.setAnimationListener(largeIconAnimateListener);

		sexIconAnimation = AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.fade_in);
		sexIconAnimation.setAnimationListener(sexIconAnimateListener);

		largeMeteorAnimation = AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.meteor_up);
		largeMeteorAnimation.setAnimationListener(largeMeteorAnimateListener);
	}

	private void showUserAnimation() {
		goneView(large_icon_section);
		icon_layout.startAnimation(starInAnimation);

		starInAnimation.setAnimationListener(new AnimationEndListener() {

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				showView(large_icon_section);
				large_icon_section.startAnimation(iconAnimation);
			}
		});
	}

	private void clearAnimation() {
		large_icon_section.clearAnimation();
		large_icon.clearAnimation();
		icon_layout.clearAnimation();
	}

	private void dismissUserAnimation() {
		dismissAnimation.setAnimationListener(new AnimationEndListener() {

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				resetView();
				clearAnimation();
			}
		});
		middle_layout.startAnimation(dismissAnimation);

	}

	private void resetView() {
		goneView(R.id.no_user);
		goneView(R.id.icon_layout);
		img_layout.removeAllViews();
		nick.stopAnimate();
		age_location.stopAnimate();
		money.stopAnimate();
		nick.setText("");
		age_location.setText("");
		money.setText("");
	}

	private long startSeekTime = 0;

	private boolean isSeekValid() {
		long endTime = System.currentTimeMillis();
		if ((endTime - startSeekTime) / 1000 > 1) {
			return true;
		}
		ALLog.d("你按住的时间太短了");
		return false;
	}

	private void resetStartSeekTime() {
		startSeekTime = System.currentTimeMillis();
	}

	@Override
	public void onTouchDown() {
		// TODO Auto-generated method stub
		ALLog.d("按住了");

		if (icon_layout.getVisibility() == View.VISIBLE) {
			dismissUserAnimation();
		} else {
			clearAnimation();
			resetView();
		}
		call.setEnabled(false);

		startLargeMeteorTask();

		seekState = START_SEEK;
		seekEvent = null;

		resetStartSeekTime();

		requeqtData();

		startGalaxyAnim();
		// if(gd != null){
		// gd.start();
		// }
		gif.setImageDrawable(gd);

	}

	@Override
	public void onTouchUp() {
		// TODO Auto-generated method stub
		ALLog.d("抬起了");
		stopGalaxyAnim();
		// if(gd != null){
		// gd.stop();
		// }
		gif.setImageDrawable(null);

		seekState = STOP_SEEK;
		stopLargeMeteorTask();

		if (!isSeekValid()) {
			return;
		}

		if (seekEvent != null) {
			if (seekEvent.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
				DatingUser tmp = (DatingUser) seekEvent.getData();
				mDatingUser = tmp;
				setupUserInfo();
				ALLog.d("得到邂逅用户" + mDatingUser.getNick());
				goneView(R.id.no_user);
				showView(R.id.icon_layout);
				call.setEnabled(true);
				showUserAnimation();
			} else {
				showView(R.id.no_user);
				goneView(R.id.icon_layout);
			}
		} else {
			showView(R.id.no_user);
			goneView(R.id.icon_layout);
			call.setEnabled(false);
		}
	}

	@Override
	public void onTouchMove() {
		// TODO Auto-generated method stub
		ALLog.d("在移动");
	}

	private AnimateListener nickAnimateListener = new AnimateListener() {

		@Override
		public void onAnimateStart() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimateEnd() {
			// TODO Auto-generated method stub
			// 顯示性別之類
			// UserIconsUtil.setupIconsLayout(img_layout, mDatingUser);
			showView(img_layout);
			img_layout.startAnimation(sexIconAnimation);
		}
	};

	private AnimateListener ageLocationAnimateListener = new AnimateListener() {

		@Override
		public void onAnimateStart() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimateEnd() {
			// TODO Auto-generated method stub
			if (!TextUtils.isEmpty(mDatingUser.getCallPrice())) {
				money.animateText(mDatingUser.getCallPrice());
			}
			// money.animateText();
		}
	};

	private AnimateListener moneyAnimateListener = new AnimateListener() {

		@Override
		public void onAnimateStart() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimateEnd() {
			// TODO Auto-generated method stub

		}
	};

}
